<?php

namespace app\api\controller\course;

use app\api\controller\Controller;
use app\api\service\Message;
use think\Db;


/**
 * 预约模块
 * Class Order
 * @package app\api\controller\shop
 */
class Appoint extends Controller
{
   

    /**
     * 预约首页数据
     */
    public function index()
    {
        
        $request = Request();
        $wxapp_id = $request->param('wxapp_id');
        
        //根据课程，将团课、私教课分类  0为团课、1为私家课
        $type = $request->param('type');

        //门店id
        $shop_id = $request->param('shop_id');

        //前台传递的日期
        $dateTime = $request->param('dateTime');

        //进行判断日期属于周几。以及是否在周期内
        //获取当前日期
        $date=date('Y-m-d');
        //通过当前日期获取当前是周内第几天
        $week = date('N', strtotime($date));
        //把当前日期格式化为当天凌晨0点 年-月-日 00:00:00 ，然后获取时间戳
        $now=strtotime(date('Y-m-d 00:00:00',strtotime($date)));
        //把时间戳减去本周已过去的天数秒数，即为本周一凌晨0点
//        $Monday=$now-(($week-1)*86400);
        $Monday=$now;
        //循环7次每次加一天并存入数组中
        $datePick = [];
        for ($i=0;$i<14;$i++){
            $datePick[$i]= date('Y-m-d',$Monday);
            $Monday=$Monday+86400;
        }

        //将前台传递的时间戳，是否在周期数组内

//        if(!in_array(date('Y-m-d',$dateTime/1000),$datePick)){
//            return $this->renderError('时间参数错误');
//        }
        if(!in_array($dateTime,$datePick)){
            return $this->renderError('只能预约两周内的课程');
        }
        

        if($type == 1){
            //展示该门店下的私教教练
            $coachData = Db::name('coach')
             ->alias('co')
             ->Join('yoshop_user us','us.user_id = co.user_id','left')
             ->Join('yoshop_upload_file u','co.image_id = u.file_id')
             ->where(['co.wxapp_id'=>$wxapp_id,'co.shop_id'=>$shop_id,'co.status'=>1,'co.is_delete'=>0])
             ->field('co.coach_id,co.real_name,us.avatarUrl,u.file_name,co.skill')
             ->select()->toArray();
            foreach ($coachData as $kk=>$vv){
                $coachData[$kk]['avatarUrl'] = base_url().'/uploads/'.$vv['file_name'];
//                if (preg_match('/(uploads)/',$vv['avatarUrl'])){
//                    $coachData[$kk]['avatarUrl'] = base_url().$vv['avatarUrl'];
//                }
            }

            //选出该门店所有私教课
            $courseData = Db::name('course')
             ->alias('c')
             ->join('course_image i' ,'c.id = i.course_id')
             ->join('upload_file u' ,'i.image_id = u.file_id')
             ->group('c.id')
             ->where(['c.wxapp_id'=>$wxapp_id,'c.shop_id'=>$shop_id,'c.status'=>10,'c.type'=>1,'c.is_delete'=>0])
             ->field('c.course_name,c.id,u.file_name')
             ->select()
             ->toArray();

            foreach ($courseData as $key=>$val){
                if($val['file_name'] && $val['file_name'] != ''){
                    //返回上传图片路径
                    $service = $_SERVER['SERVER_NAME'];//域名
                    $courseData[$key]['file_name'] = base_url()."/uploads/".$val['file_name'];
                }else{
                    $courseData[$key]['file_name'] = '';
                }
            }



            return $this->renderSuccess([
                'coachData' => $coachData,  // 教练数据
                'courseData'=> $courseData, // 课程数据
            ]);
        }
        //团课
        if($type == 0){
            //展示门店团课。以及当天 可以预约的团课  以及已经预约的人数

            //时间戳转周几
//            $week = date('w',$dateTime/1000);
            $week = date('w',strtotime($dateTime));
            if($week == 0){
                $week = 7; //周日
            }

            $where[] = ['exp',Db::raw("FIND_IN_SET($week,c.week)")];//category值为数字，例子：419,415,414
            $courseData = Db::name('course')
             ->alias('c')
             ->join('course_image i' ,'c.id = i.course_id')
             ->join('upload_file u' ,'i.image_id = u.file_id')
             ->Join('coach ch','c.coach_id = ch.coach_id')
             ->group('c.id')
             ->where(['c.wxapp_id'=>$wxapp_id,'c.shop_id'=>$shop_id,'c.status'=>10,'c.type'=>2,'c.is_delete'=>0])
             ->where($where)
             ->field('ch.real_name,c.course_name,c.id,c.time,c.people,c.time,u.file_name')
             ->select()
             ->toArray();

             

             //查询该天已经有多少人报名该团课
            if($courseData){
                foreach ($courseData as $key=>$val){
                    if($val['file_name'] && $val['file_name'] != ''){
                        //返回上传图片路径
                        $service = $_SERVER['SERVER_NAME'];//域名
                        $courseData[$key]['file_name'] = base_url()."/uploads/".$val['file_name'];
                    }else{
                        $courseData[$key]['file_name'] = '';
                    }
                }
                foreach ($courseData as $key => $value) {
                    $courseData[$key]['appoint_people_num'] = Db::name('course_reservation')->where(['course_id'=>$value['id'],'date'=>$dateTime,'time'=>$value['time']])->where('status','neq',3)->count('id');
                    $courseData[$key]['date'] = $dateTime;
                }
            }
            return $this->renderSuccess([
                'courseData'=> $courseData, // 课程数据
            ]);
        }  

    }

    //团购卡展示(团卡)
    public function courseGroup(){
        $request = Request();
        $wxapp_id = $request->param('wxapp_id');

        $course_id = $request->Param('id');//课程id
        $date = $request->Param('date');

        //查看该用户，是否已经授权
        $userData = $this->getUser();

        $courseData = Db::name('course')->where(['id'=>$course_id])->find();


        //查看用户是否已经购买了团课卡
        $courseGroup = Db::name('course_order_detail')
             ->alias('d')
             ->join('yoshop_course_card_image i' ,'d.image_id = i.image_id')
             ->join('yoshop_upload_file u' ,'i.image_id = u.file_id')
             ->where(['d.wxapp_id'=>$wxapp_id,'d.shop_id'=>$courseData['shop_id']])
             ->where(['d.type'=>2,'d.user_id'=>$userData['user_id'],'d.card_status'=>['in',[1,2]],'d.is_delete'=>0])
             ->field('d.*,u.file_name')
             ->select()->toArray();

        if(!$courseGroup){
             return $this->renderError('请购买团购卡');
        }
        foreach ($courseGroup as $key=>$val){
            if($val['file_name'] && $val['file_name'] != ''){
                //返回上传图片路径
                $service = $_SERVER['SERVER_NAME'];//域名
                $courseGroup[$key]['file_name'] = base_url()."/uploads/".$val['file_name'];
            }else{
                $courseGroup[$key]['file_name'] = '';
            }
        }

        return $this->renderSuccess([
            'courseGroup'=> $courseGroup, //
            'course_id'=>$course_id,
            'date'     => $date

        ]);




    }

    //用户点击预约(团卡)
    public function appoint(){
        $request = Request();
        $wxapp_id = $request->param('wxapp_id');

        $course_id = $request->Param('course_id');//课程id
        $date = $request->Param('date');

        $course_order_id = $request->param('course_order_id');//用户选择核销的团课卡id
        if(!$course_order_id){
            return $this->renderError('卡参数不能为空');
        }
        //查看该用户，是否已经授权
        $userData = $this->getUser();
        if ($userData['phone'] == ''){
            return $this->renderError('还未绑定手机号','');
        }

        $groupCourse = Db::name('course_order_detail')->where(['course_order_id'=>$course_order_id,'user_id'=>$userData['user_id'],'type'=>2,'is_delete'=>0])->find();

        if(!$groupCourse){
            return $this->renderError('课程卡不存在');
        }
        if ($groupCourse['is_active'] == 0){
            return $this->renderError('课程卡未激活');
        }
        if ($groupCourse['card_status'] == 0){
            return $this->renderError('课程卡未付款');
        }
        if ($groupCourse['card_status'] == 4){
            return $this->renderError('课程卡已过期');
        }
        if ($groupCourse['card_status'] == 5){
            return $this->renderError('课程卡已停用');
        }

        //查看该团课卡次数是否足够
        if($groupCourse['remain_nums'] == 0){
            return $this->renderError('卡次数已为0');
        }

        $courseData = Db::name('course')->where(['id'=>$course_id])->find();


        $courseUserRes = Db::name('course_reservation')
            ->where(['wxapp_id'=>$wxapp_id,'course_id'=>$course_id,'user_id'=>$userData['user_id'],'date'=>$date])
            ->where('status','neq',3)
            ->find();
        if($courseUserRes){
             return $this->renderError('请勿重复预约');
        }
        
        //查看可能是否已满
        //查看该可能已经预约的人数
        $is_appoint_num = Db::name('course_reservation')
            ->where(['wxapp_id'=>$wxapp_id,'course_id'=>$course_id,'date'=>$date])
            ->where('status','neq',3)
            ->count();


        if($is_appoint_num  == $courseData['people']){
             return $this->renderError('人数已满');
        }

        //当天时间，是否提前三小时预约课程开始时间，如果已经过了，不能预约  。 第二天时间段不受影响
        $todayData = date('Y-m-d');
        if($todayData ==  $date){
            $beg = explode('~',$courseData['time']);
            $appTime = strtotime($date.$beg[0].":00")-3600*3;
            if(time() > $appTime){
                return $this->renderError('预约已超时');
            }
        }
        
        //保存数据
        $add['course_id'] = $courseData['id'];
        $add['user_id']   = $userData['user_id'];
        $add['coach_id']  = $courseData['coach_id'];
        $add['date']      = $date;
        $add['time']      = $courseData['time'];
        $add['shop_id']   = $courseData['shop_id'];
        $add['wxapp_id']  = $wxapp_id;
        $add['create_time'] = time();


        $betTime = explode('~',$courseData['time']);
        //增加beg 和 end 时间
        $add['start_time'] = $date." ".$betTime[0];
        $add['end_time']   = $date." ".$betTime[1]; 
        $add['course_order_id']  = $groupCourse['course_order_id'];


        Db::name('course_reservation')->insert($add);

        //扣除卡一次  判断卡是否已开
        if($groupCourse['nums'] == $groupCourse['remain_nums']){
            //未开卡，这时将卡有效期以及次数更新
            $up['remain_nums'] = $groupCourse['nums'] -1;
            $up['card_status']  = 2;//开始生效
            $up['start_time']  = time();
            $up['expire_time'] =strtotime(date('Y-m-d ',time()+$groupCourse['days']*24*3600))+86399;
            Db::name('course_order_detail')->where(['course_order_id'=>$groupCourse['course_order_id']])->update($up);
        }else{

            $up['remain_nums'] = $groupCourse['remain_nums'] -1;
            if($up['remain_nums'] == 0){
                $up['card_status'] = 3;
            }


            Db::name('course_order_detail')->where(['course_order_id'=>$groupCourse['course_order_id']])->update($up);
        }
        //2023 03 22 发送公众号推送
        $this->GZSend($userData,$courseData['coach_id'],$date." ".$courseData['time'],$courseData['course_name']);
        return $this->renderSuccess([],'预约成功');

    }


    //私教一对一预约
    public function privateCourse(){
         $request = Request();
        //参数
        $wxapp_id = $request->param('wxapp_id');
        $course_id = $request->Param('course_id');//课程id
        $coach_id = $request->Param('coach_id');//教练id
         //门店id
        $shop_id = $request->param('shop_id');

        if(empty($coach_id)){
            return $this->renderError('请选择教练');
        }
        if(empty($course_id)){
            return $this->renderError('请选择课程');
        }
        //选出该门店所有私教课
        $courseData = Db::name('course')
         ->alias('c')
         ->join('course_image i' ,'c.id = i.course_id')
         ->join('upload_file u' ,'i.image_id = u.file_id')
         ->group('c.id')
         ->where(['c.wxapp_id'=>$wxapp_id,'c.shop_id'=>$shop_id,'c.status'=>10,'c.type'=>1,'c.id'=>$course_id,'c.is_delete'=>0])
         ->field('c.course_name,c.id,u.file_name')
         ->find();
      
        $service = $_SERVER['SERVER_NAME'];//域名
        $courseData['file_name'] = base_url()."/uploads/".$courseData['file_name'];
   

        //前台传递的日期
        $dateTime = $request->param('dateTime');

        //进行判断日期属于周几。以及是否在周期内
        //获取当前日期
        $date=date('Y-m-d');
        //通过当前日期获取当前是周内第几天
        $week = date('N', strtotime($date));
        //把当前日期格式化为当天凌晨0点 年-月-日 00:00:00 ，然后获取时间戳
        $now=strtotime(date('Y-m-d 00:00:00',strtotime($date)));
        //把时间戳减去本周已过去的天数秒数，即为本周一凌晨0点
//        $Monday=$now-(($week-1)*86400);
        $Monday = $now;
        //循环7次每次加一天并存入数组中
        for ($i=0;$i<=14;$i++){
            $datePick[$i]= date('Y-m-d',$Monday);
            $Monday=$Monday+86400;
        }


        //将前台传递的时间戳，是否在周期数组内

        if(!in_array(date('Y-m-d',$dateTime/1000),$datePick)){
            return $this->renderError('请选择两周内的课程');
        }
        $t1 = strtotime(date('Y-m-d',$dateTime/1000).'08:00');
        $t2 = strtotime(date('Y-m-d',$dateTime/1000).'21:00');

        $timeslots = array();
 
        while ($t1 < $t2) {
            $t1 = $t1 + 3600;
            $timeslots[] = $t1;
        }
        $betTime = array();
        foreach ( $timeslots as $slot ) {
            $betTime[] = date("H:i",$slot);
        }

        $reData = array();
        //查看选择的日期，选择的教练 预约情况
        $now = time();
        if(date('Y-m-d',$dateTime/1000) == date('Y-m-d')){
            //当天时间，查看是否超时
            foreach ($betTime as $key => $value) {
                $reData[$key]['time'] = $value;
                if(strtotime(date('Y-m-d').$value) < time()){
                    $reData[$key]['type'] = -1;//已过期
                }else{
                    //查询该时间点，是否被预约了
                    $timeRes = Db::name('course_reservation')
                       ->where(['wxapp_id'=>$wxapp_id,'shop_id'=>$shop_id,'course_id'=>$course_id,'coach_id'=>$coach_id])
                       ->where(['date'=>date('Y-m-d',$dateTime/1000)])
                       ->where(['time'=>$value])
                       ->where('status','neq',3)
                       ->find();
                    if($timeRes){
                        $reData[$key]['type'] = 1;//已被预约
                    }else{
                        $start = date("Y-m-d ".$value);
                        if ($now >= (strtotime($start) - 3*60*60) && $now <= strtotime($start)){
                            $reData[$key]['type'] = -2;//3小时内不可预约
                        }else{
                            $reData[$key]['type'] = 0;//可以预约
                        }

                    }
                }
            }
        }else{
            foreach ($betTime as $key => $value) {
                $reData[$key]['time'] = $value;
                //查询该时间点，是否被预约了
                $timeRes = Db::name('course_reservation')
                   ->where(['wxapp_id'=>$wxapp_id,'shop_id'=>$shop_id,'course_id'=>$course_id,'coach_id'=>$coach_id])
                   ->where(['date'=>date('Y-m-d',$dateTime/1000)])
                   ->where(['time'=>$value])
                   ->where('status','neq',3)
                   ->find();
                if($timeRes){
                    $reData[$key]['type'] = 1;//已被预约
                }else{
                    $reData[$key]['type'] = 0;//可以预约
                }

            }
        }
        
        return $this->renderSuccess([
            'data'=> $reData, //时间数据
            'courseData' => $courseData,//课程数据
            'course_id'=>$course_id,
            'shop_id'     => $shop_id,
            'coach_id' => $coach_id,
            'date'     =>date('Y-m-d',$dateTime/1000),
        ]);


    }



    //一对一卡展示(私卡卡)
    public function coursePrivateList(){
        $request = Request();
        $wxapp_id = $request->param('wxapp_id');

        $course_id = $request->Param('course_id');//课程id
        $date = $request->Param('date');
        $time  = $request->param('time');
        $shop_id  = $request->param('shop_id');
        $coach_id  = $request->param('coach_id');
        


        //查看该用户，是否已经授权
        $userData = $this->getUser();
        if ($userData['phone'] == ''){
            return $this->renderError('还未绑定手机号','');
        }
        $courseData = Db::name('course')->where(['id'=>$course_id])->find();
        if(!$courseData){
            return $this->renderError('课程卡不存在');
        }

        if($courseData['shop_id'] != $shop_id){
            return $this->renderError('参数不匹配');
        }

        //查看用户是否已经购买了团课卡
        $courseGroup = Db::name('course_order_detail')
             ->alias('d')
             ->join('upload_file u' ,'d.image_id = u.file_id')
             ->where(['d.wxapp_id'=>$wxapp_id,'d.shop_id'=>$shop_id ])
             ->where(['d.type'=>1,'d.user_id'=>$userData['user_id'],'d.card_status'=>['in',[1,2,3]],'d.is_delete'=>0])
             ->field('d.*,u.file_name')
             ->select()
             ->toArray();

        if(!$courseGroup){
             return $this->renderError('请购买私教卡');
        }
        foreach ($courseGroup as $key=>$val){
            if($val['file_name'] && $val['file_name'] != ''){
                //返回上传图片路径
                $service = $_SERVER['SERVER_NAME'];//域名
                $courseGroup[$key]['file_name'] = base_url()."/uploads/".$val['file_name'];
            }else{
                $courseGroup[$key]['file_name'] = '';
            }
        }

        return $this->renderSuccess([
            'coursePrivate'=> $courseGroup, //
            'course_id'=>$course_id,
            'date'     => $date,
            'time'     => $time,
            'coach_id' => $coach_id,
            'shop_id'  => $shop_id,

        ]);

    }


     //私教一对一提交
    public function privateCourseSure(){
         $request = Request();
        //参数
        $wxapp_id = $request->param('wxapp_id');
        $course_id = $request->Param('course_id');//课程id
        $coach_id = $request->Param('coach_id');//教练id
         //门店id
        $shop_id = $request->param('shop_id');

        if(empty($coach_id)){
            return $this->renderError('请选择教练');
        }
         if(empty($shop_id)){
            return $this->renderError('门店参数不能为空');
        }
        if(empty($course_id)){
            return $this->renderError('请选择课程');
        }

        $dateQ = $request->Param('date');
        $time = $request->param('time');

        if(empty($dateQ)){
            return $this->renderError('预约日期不能为空');
        }
        if(empty($time)){
            return $this->renderError('预约时间不能为空');
        }

        // //进行判断日期属于周几。以及是否在周期内
        // //获取当前日期
        // $date=date('Y-m-d');
        // //通过当前日期获取当前是周内第几天
        // $week = date('N', strtotime($date));
        // //把当前日期格式化为当天凌晨0点 年-月-日 00:00:00 ，然后获取时间戳
        // $now=strtotime(date('Y-m-d 00:00:00',strtotime($date)));
        // //把时间戳减去本周已过去的天数秒数，即为本周一凌晨0点
        // $Monday=$now-(($week-1)*86400);
        // //循环7次每次加一天并存入数组中
        // for ($i=0;$i<7;$i++){
        //     $datePick[$i]= date('Y-m-d',$Monday);
        //     $Monday=$Monday+86400;
        // }
        // //将前台传递的时间戳，是否在周期数组内

        // if(!in_array($dateQ,$datePick)){
        //     return $this->renderError('时间参数错误');
        // }

        $course_order_id = $request->param('course_order_id');//用户选择核销的私课卡id
        if(empty($course_order_id)){
            return $this->renderError('购卡参数不能为空');
        }

        //查看该用户，是否已经授权
        $userData = $this->getUser();
        if ($userData['phone'] == ''){
            return $this->renderError('还未绑定手机号');
        }

        $groupCourse = Db::name('course_order_detail')->where(['course_order_id'=>$course_order_id,'user_id'=>$userData['user_id'],'type'=>1,'is_delete'=>0])->find();

        if(!$groupCourse){
            return $this->renderError('课程卡不存在');
        }
        if ($groupCourse['is_active'] == 0){
            return $this->renderError('课程卡未激活');
        }
        if ($groupCourse['card_status'] == 0){
            return $this->renderError('课程卡未付款');
        }
        if ($groupCourse['card_status'] == 4){
            return $this->renderError('课程卡已过期');
        }
        if ($groupCourse['card_status'] == 5){
            return $this->renderError('课程卡已停用');
        }

        //查看该团课卡次数是否足够
        if($groupCourse['remain_nums'] == 0){
            return $this->renderError('卡次数已为0');
        }

        $courseData = Db::name('course')->where(['id'=>$course_id])->find();

        $courseUserRes = Db::name('course_reservation')
            ->where(['wxapp_id'=>$wxapp_id,'course_id'=>$course_id,'user_id'=>$userData['user_id'],'date'=>$dateQ,'time'=>$time,'coach_id'=>$coach_id])
            ->where('status','neq',3)
            ->find();
        if($courseUserRes){
             return $this->renderError('请勿重复预约');
        }
        
        //查看可能是否已满
        //查看该可能已经预约的人数
        $is_appoint_num = Db::name('course_reservation')
            ->where(['wxapp_id'=>$wxapp_id,'course_id'=>$course_id,'date'=>$dateQ,'time'=>$time,'coach_id'=>$coach_id])
            ->where('status','neq',3)
            ->find();


        if($is_appoint_num){
            return $this->renderError('该时间段已经被预约');
        }

        //过期的时间不能预约
        $todayTime = time();

        $appTime = strtotime($dateQ.$time);
        if($todayTime  > $appTime){
            return $this->renderError('该时间段已超时');
        }
        //2023 03 10 开始前3小时不能预约
        if ($todayTime >= ($appTime - 3*60*60)){
            return $this->renderError('开课前3小时不能预约');
        }
        
        //保存数据
        $add['course_id'] = $courseData['id'];
        $add['user_id']   = $userData['user_id'];
        $add['coach_id']  = $coach_id;
        $add['date']      = $dateQ;
        $add['time']      = $time;
        $add['shop_id']   = $courseData['shop_id'];
        $add['wxapp_id']  = $wxapp_id;
        $add['create_time'] = time();

        $add['start_time'] = $dateQ." ".$time;
        $add['end_time']   = date("Y-m-d H:i", strtotime( $add['start_time'].' +1 hour'));
        $add['course_order_id']  = $groupCourse['course_order_id'];


        Db::name('course_reservation')->insert($add);

        //扣除卡一次  判断卡是否已开
        if($groupCourse['nums'] == $groupCourse['remain_nums']){
            //未开卡，这时将卡有效期以及次数更新
            $up['remain_nums'] = $groupCourse['nums'] -1;
            $up['start_time']  = time();
            $up['card_status']  = 2;//开始生效
            $up['expire_time'] =strtotime(date('Y-m-d ',time()+$groupCourse['days']*24*3600))+86399;
            Db::name('course_order_detail')->where(['course_order_id'=>$groupCourse['course_order_id']])->update($up);
        }else{
            $up['remain_nums'] = $groupCourse['remain_nums'] -1;
            if($up['remain_nums'] == 0){
                $up['card_status'] = 3;
            }
            Db::name('course_order_detail')->where(['course_order_id'=>$groupCourse['course_order_id']])->update($up);
        }
        //2023 03 22 发送公众号推送
        $this->GZSend($userData,$coach_id,$dateQ." ".$time."~".date('H:i',strtotime($add['end_time'])),$courseData['course_name']);
        return $this->renderSuccess([],'预约成功');

    }

    public function test(){
        $msg = new Message();
        $msg->index();
        die;
        $userData = Db::name('user')->find(10005);
        $coach_id = 11;$dateQ = "2023-03-22";$time = "19:00";$courseData['course_name'] = '拳击';$add['end_time'] = "2023-03-17 21:00";
        $this->GZSend($userData,$coach_id,$dateQ." ".$time."~".date('H:i',strtotime($add['end_time'])),$courseData['course_name']);
    }

    public function GZSend($user,$coach_id,$reservation_time,$course_name){
        $params = [];
        $coach = \app\store\model\store\shop\Coach::detail(['coach_id'=>$coach_id]);
        if ($coach['user']['gz_open_id'] != ''){
            //获取到了公众号openid
            $params['gz_open_id'] = $coach['user']['gz_open_id'];
            $params['nickName'] = $user['nickName'];
            $params['coachName'] = $coach['real_name'];
            $params['reservation_time'] = $reservation_time;
            $params['remark'] = '预约课程：'.$course_name;
            $message = new Message();
            $message->send($params);
        }
    }





}